package org.september.pisces.user.permission.controller;

import static java.util.stream.Collectors.toList;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.september.core.constant.SpecialCharConst;
import org.september.core.constant.enums.DeleteFlag;
import org.september.core.exception.BusinessException;
import org.september.core.util.MD5;
import org.september.core.util.PasswordUtil;
import org.september.pisces.user.permission.entity.Department;
import org.september.pisces.user.permission.entity.SystemRole;
import org.september.pisces.user.permission.entity.SystemUser;
import org.september.pisces.user.permission.service.DeptService;
import org.september.pisces.user.permission.service.OperationLogService;
import org.september.pisces.user.permission.service.SystemUserService;
import org.september.pisces.user.permission.service.UserOnlineStatusService;
import org.september.pisces.user.permission.utils.UserSessionHelper;
import org.september.simpleweb.auth.DefaultMethod;
import org.september.simpleweb.model.ResponseVo;
import org.september.smartdao.CommonDao;
import org.september.smartdao.CommonValidator;
import org.september.smartdao.model.Page;
import org.september.smartdao.model.ParamMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import jakarta.validation.Valid;

@Controller
public class PiscesSystemUserController {

	@Autowired
	private CommonValidator commonValidator;
	
	@Autowired
	private CommonDao commonDao;
	
	@Autowired
	private UserOnlineStatusService userOnlineStatusService;
	
	@Autowired
	private SystemUserService systemUserService;
	
	@Autowired
	private OperationLogService operationLogService;
	
	@Autowired
	private DeptService deptService;

	@RequestMapping(List_Page)
	public ModelAndView systemUserList() throws Exception {
		ModelAndView mv = new ModelAndView();
		return mv;
	}

	@ResponseBody
	@RequestMapping(List_Data)
	public ResponseVo<Page<SystemUser>> systemUserListData(Long deptId, String realname, Page<SystemUser> page) throws Exception {
		SystemUser vo = new SystemUser();
		vo.setDeleteFlag(DeleteFlag.NotDelete.ordinal());
		ParamMap pm = new ParamMap();
		Department department = commonDao.get(Department.class, deptId);
		if(deptId!=null && department!=null) {
			pm.put("fullDeptId", department.getFullId());
		}
		pm.put("realname", realname);
		page = commonDao.findPageByParams(SystemUser.class, page, "PiscesSystemUser.systemUserListData", pm);
		for(SystemUser su : page.getResult()) {
			if(userOnlineStatusService.isUserWebOnline(su.getId())) {
				su.setWebOnline("在线");
			}
			if(userOnlineStatusService.isUserAppOnline(su.getId())) {
				su.setAppOnline("在线");
			}
		}
		return ResponseVo.<Page<SystemUser>>BUILDER().setData(page).setCode(ResponseVo.BUSINESS_CODE.SUCCESS);

	}

	@RequestMapping(value = Add_Page)
	public ModelAndView addSystemUser(Long deptId) throws Exception {
		ModelAndView mv = new ModelAndView();
		mv.addObject("deptId", deptId);
		Department dept = commonDao.get(Department.class, deptId);
		if(dept==null) {
			throw new BusinessException("部门信息错误");
		}
		mv.addObject("deptName", dept.getName());
		prepareAllRoles(mv);
		return mv;
	}

	@ResponseBody
	@PostMapping(Add_Action)
	public ResponseVo<String> doAddSystemUser(@Valid SystemUser systemUser) throws Exception {
		if (StringUtils.isEmpty(systemUser.getRoleIds())) {
			throw new BusinessException("请先选择角色");
		}
		
		boolean exist = commonValidator.exsits(SystemUser.class, new String[]{"phone","deleteFlag"}, new Object[]{systemUser.getPhone(),DeleteFlag.NotDelete.ordinal()});		if (exist) {
			throw new BusinessException("手机号码重复，请检查!");
		}
		
		Department dept = deptService.getDepartmentByName(systemUser.getDeptName());
		if(dept==null) {
			throw new BusinessException("用户所属部门不存在，请检查!");
		}
		systemUser.setFullDeptId(dept.getFullId());
		systemUser.setDeptId(dept.getId());
		systemUserService.addUser(systemUser);
		operationLogService.addLog("添加了用户【"+systemUser.getUsername()+"】");
		return ResponseVo.<String>BUILDER().setData("").setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
	}

	
	@RequestMapping(value = Edit_Page)
	public ModelAndView editSystemUser(Long id) throws Exception {
		ModelAndView mv = new ModelAndView();
		SystemUser po = commonDao.get(SystemUser.class, id);
		mv.addObject("systemUser", po);
		Department dept = commonDao.get(Department.class, po.getDeptId());
		po.setDeptName(dept.getName());
		List<Long> userRoleIdList = new ArrayList<>();
		if (po.getRoleIds() != null) {
			String[] arr = po.getRoleIds().split(";");
			userRoleIdList = Arrays.stream(arr).filter(x -> !StringUtils.isEmpty(x)).map(Long::valueOf).collect(toList());
		}
		mv.addObject("urIdList", userRoleIdList);
		prepareAllRoles(mv);
		return mv;
	}

	@ResponseBody
	@PostMapping(Edit_Action)
	public ResponseVo<String> doUpdateSystemUser(@Valid SystemUser systemUser) throws Exception {
		boolean exist = commonValidator.exsitsNotMe(SystemUser.class, new String[]{"username","deleteFlag"}, new Object[]{systemUser.getUsername(),DeleteFlag.NotDelete.ordinal()}, systemUser.getId());
		if (exist) {
			throw new BusinessException("账号重复，请检查!");
		}
		Department dept = deptService.getDepartmentByName(systemUser.getDeptName());
		if(dept==null) {
			throw new BusinessException("用户所属部门不存在，请检查!");
		}
		SystemUser po = commonDao.get(SystemUser.class, systemUser.getId());
		systemUser.setFullDeptId(po.getFullDeptId());//从数据库查出来
		systemUser.setDeptId(po.getDeptId());
		if (!systemUser.getRoleIds().endsWith(SpecialCharConst.Semicolon)) {
			systemUser.setRoleIds(systemUser.getRoleIds() + SpecialCharConst.Semicolon);
		}
		if (!systemUser.getRoleIds().endsWith(SpecialCharConst.Semicolon)) {
			systemUser.setRoleIds(systemUser.getRoleIds() + SpecialCharConst.Semicolon);
		}
		commonDao.update(systemUser);

		operationLogService.addLog("修改了用户【"+systemUser.getUsername()+"】的信息");
		return ResponseVo.<String>BUILDER().setData("").setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
	}

//	@PiscesPermission(path=UserPermissionModule.Menu_User+"-分配点位")
//    @ResponseBody
//    @RequestMapping(value = "/assignStations")
//    public ResponseVo<String> assignStations(Long id , String stationIds) throws Exception {
//		SystemUser su = commonDao.get(SystemUser.class, id);
//    	if(su==null) {
//    		throw new BusinessException("用户不存在！");
//    	}
//    	su.setStationIds(stationIds);
//    	commonDao.update(su);
//        return ResponseVo.<String> BUILDER().setData("").setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
//    }
	
	@ResponseBody
	@RequestMapping(value = Delete_Action)
	public ResponseVo<String> delete(Long id) throws Exception {
		SystemUser po = commonDao.get(SystemUser.class, id);
		if (po == null) {
			throw new RuntimeException("数据不存在或已删除");
		}
		commonDao.delete(po);
		operationLogService.addLog("删除了用户【"+po.getUsername()+"】");
		return ResponseVo.<String>BUILDER().setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
	}


	@DefaultMethod
	@RequestMapping(value = Reset_Password_Page)
	public ModelAndView resetMyPwd() throws Exception {
		ModelAndView mv = new ModelAndView();
		mv.addObject("id", UserSessionHelper.getLoginUid());
		return mv;
	}

	@DefaultMethod
	@ResponseBody
	@RequestMapping(value = Reset_Password_Action)
	public ResponseVo<String> doResetMyPwd(Long id, String oldPwd, String newPwd, String newPwdRepeat) throws Exception {
		systemUserService.doResetMyPwd(id, oldPwd, newPwd, newPwdRepeat);
		return ResponseVo.<String>BUILDER().setData("").setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
	}


	private void prepareAllRoles(ModelAndView mv) {
		SystemRole roleVo = new SystemRole();
		roleVo.setDeleteFlag(DeleteFlag.NotDelete.ordinal());
		List<SystemRole> roles = commonDao.listByExample(roleVo);
		mv.addObject("roles", roles);
	}
	
	private static final String Mapping_Prefix = "/userPermission/systemUser";
	
	public static final String List_Page = Mapping_Prefix+"/systemUserList";
	public static final String List_Data = Mapping_Prefix+"/systemUserListData";
	
	public static final String Add_Page = Mapping_Prefix+"/addSystemUser";
	public static final String Add_Action = Mapping_Prefix+"/doAddSystemUser";
	
	public static final String Edit_Page = Mapping_Prefix+"/editSystemUser";
	public static final String Edit_Action = Mapping_Prefix+"/doUpdateSystemUser";
	
	public static final String Reset_Password_Page = Mapping_Prefix+"/resetMyPwd";
	public static final String Reset_Password_Action = Mapping_Prefix+"/doResetMyPwd";
	
	public static final String Delete_Action = Mapping_Prefix+"/delete";
	
}
